import cv2
import numpy as np
import matplotlib.pyplot as plt


# 反相灰度图，将黑白阈值颠倒
def accessPiexl(img):
    height = img.shape[0]
    width = img.shape[1]
    for i in range(height):
        for j in range(width):
            img[i, j] = 255 - img[i, j]
    return img


# 反相二值化图像
def accessBinary(img, threshold=128):
    img = accessPiexl(img)
    # 边缘膨胀，不加也可以
    kernel = np.ones((3, 3), np.uint8)
    img = cv2.dilate(img, kernel, iterations=1)
    _, img = cv2.threshold(img, threshold, 0, cv2.THRESH_TOZERO)
    return img


# 绘制像素求和折线图
def plot_sum_lines(img):
    row_sum = np.sum(img, axis=1)
    col_sum = np.sum(img, axis=0)

    plt.figure(figsize=(12, 6))

    # 绘制列求和折线图
    plt.subplot(1, 2, 1)
    plt.plot(col_sum, label='Column Sum')
    plt.title('Sum of Pixels by Column')
    plt.xlabel('Column Index')
    plt.ylabel('Sum of Pixels')
    plt.legend()

    # 绘制行求和折线图，交换横纵坐标
    plt.subplot(1, 2, 2)
    plt.plot(row_sum, np.arange(len(row_sum)), label='Row Sum')
    plt.gca().invert_yaxis()  # 反转Y轴，使行索引从上到下增加
    plt.title('Sum of Pixels by Row (Inverted Coordinates)')
    plt.xlabel('Sum of Pixels')
    plt.ylabel('Row Index')
    plt.legend()

    plt.tight_layout()
    plt.show()


path = './test_img/test4.jpg'
img = cv2.imread(path, 0)
img = accessBinary(img)
cv2.imshow('accessBinary', img)
cv2.waitKey(0)
cv2.destroyAllWindows()

# 对处理后的图像进行每行、每列的像素求和并绘制折线图
plot_sum_lines(img)
